package com.cloudbroker.bcs.platform.dav.configure.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.configure.ConfigUtil;
import com.cloudbroker.bcs.common.configure.HSBCSZooKeeperConfigLoader;
import com.cloudbroker.bcs.common.configure.HSBCSZooKeeperConfigurator;
import com.cloudbroker.bcs.common.context.DataContext;
import com.cloudbroker.bcs.common.context.RuntimeContext;
import com.cloudbroker.bcs.platform.dav.configure.define.XMLConfigParser;
import com.cloudbroker.bcs.platform.dav.configure.service.PersistenceService;
import com.cloudbroker.bcs.platform.dav.configure.service.TenantManager;

public class OperationServlet extends HttpServlet {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(OperationServlet.class);
    
    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = 1L;
    
    private String indexPage;
    
    private String modifyPage;
    
    private String managerPage;
    
    @Override
    public void init(ServletConfig config) throws ServletException {
        indexPage = config.getServletContext().getContextPath() + "/configure-index.jsp";
        modifyPage = config.getServletContext().getContextPath() + "/configure.jsp";
        managerPage = config.getServletContext().getContextPath() + "/configure-manager.jsp";
        
        HSBCSZooKeeperConfigLoader zkConfigLoader = RuntimeContext.getBean(HSBCSZooKeeperConfigLoader.class);
        HSBCSZooKeeperConfigurator zkConfigurator = zkConfigLoader.getZkConfigurator();
        if (null != zkConfigurator) {
            PersistenceService.init(zkConfigurator);
            TenantManager.setZkConfigurator(zkConfigurator);
        } else {
            LOGGER.warn("no zkConfigurator exists, will not write to zookeeper");
        }
    }
    
    @Override
    public void destroy() {
        PersistenceService.dispose();
    }
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = req.getRequestURI();
        if (-1 != url.indexOf('.')) {
            return;
        }
        
        String func = null;
        int lastSlashIdx = url.lastIndexOf('/');
        if (-1 != lastSlashIdx) {
            func = url.substring(lastSlashIdx + 1);
        } else {
            func = "";
        }
        
        if (StringUtils.isBlank(DataContext.getTenantId())) {
            if ("manage".equals(func)) {
                handleManager(req, resp);
            } else if ("delete".equals(func)) {
                handleDelete(req, resp);
            }
        } else {
            if ("index".equals(func)) {
                handleIndex(req, resp);
            } else if ("toModify".equals(func)) {
                handleToModify(req, resp);
            } else if ("save".equals(func)) {
                handleSave(req, resp);
            }
        }
    }
    
    private void handleIndex(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher(indexPage).forward(req, resp);
    }
    
    private void handleToModify(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        req.getRequestDispatcher(modifyPage).forward(req, resp);
    }
    
    private void handleSave(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JSONObject result = new JSONObject();
        Map<String, String> params = getParameterMap(req);
        String catalogId = params.remove("catalogId");
        XMLConfigParser.generateTemplateFile(params, catalogId);
        
        int code = 0;
        if (!ConfigUtil.isNoTenant()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //code = PersistenceService.saveOriConfigDataToDB(params);
        }
        result.put("errorNo", code);
        
        PrintWriter writer = resp.getWriter();
        writer.write(result.toJSONString());
        writer.flush();
    }
    
    public Map<String, String> getParameterMap(HttpServletRequest request) {
        Map<String, String[]> paramMap = request.getParameterMap();
        // 返回值Map
        Map<String, String> returnMap = new HashMap<String, String>();
        
        for (Entry<String, String[]> paramEntry : paramMap.entrySet()) {
            String paramName = paramEntry.getKey();
            String paramValue = null;
            String[] paramValues = paramEntry.getValue();
            if (null == paramValues || 0 == paramValues.length) {
                paramValue = "";
            } else {
                paramValue = StringUtils.join(paramValues, ',');
            }
            returnMap.put(paramName, paramValue);
        }
        return returnMap;
    }
    
    private void handleManager(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        req.getRequestDispatcher(managerPage).forward(req, resp);
    }
    
    /**
     * 删除所配置的租户
     */
    private void handleDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        // 租户ID
        String tenantId = req.getParameter("tenantId");
        // 执行删除操作,将配置信息从ZooKeeper中删除
        TenantManager.deleteConfig(tenantId);
    }
    
}
